layui.use(['jquery', 'laydate', 'layer', 'form', 'table', 'util', 'configs', 'template', 'cookie', 'excel'], function () {
    var $ = layui.jquery,
        laydate = layui.laydate,
        layer = layui.layer,
        form = layui.form,
        table = layui.table,
        util = layui.util,
        template = layui.template,
        config = layui.configs,
        cookie = layui.cookie,
        excel = layui.excel;
    var tableRender = null, areaId = null, searchParams = null, page = 1, limit = 10, total = 0, filterObj = {};
    var mo_cookie = sessionStorage.getItem("this_motor");
    var this_motor = null, limit = 10, total = 0, curr = 1;
    if (mo_cookie != null && mo_cookie != "" && mo_cookie != undefined) {
        this_motor = JSON.parse(mo_cookie);
    }
    initAll();

    function initAll() {
        initDate();
        getArea();
        //$(".searchBtn").click();
    }

    //获取区域
    function getArea() {
        $.ajax({
            url: config.motorBaseUrl + "/area_info/select/v1.0",
            type: "post",
            datatype: "json",
            async: false,
            data: {},
            success: function (result) {
                if (result.stateCode == 0) {
                    $(".areaMenu").html(template("motor-areas-tpl", result));
                    if (this_motor != null) {
                        form.val('parameter', {
                            "areaId": this_motor.areaId
                        });
                        form.render('select');
                        areaId = this_motor.areaId;
                        getMotors(areaId);
                    } else {
                        form.render('select');
                    }
                } else {
                    layer.alert(result.stateMsg);
                }
            }
        })
    }

    // 按区域查马达
    function getMotors(areaId) {
        $.ajax({
            url: config.motorBaseUrl + "/mo_motors/selectMortor/v1.0",
            type: "post",
            datatype: "json",
            async: false,
            data: {
                areaId: areaId
            },
            success: function (result) {
                if (result.stateCode == 0) {
                    $(".motorMenu").html(template("motors-tpl", result));
                    if (this_motor != null) {
                        form.val('parameter', {
                            "moId": this_motor.moId
                        });
                        form.render('select');
                        $(".searchBtn").click();
                    } else {
                        form.render('select');
                    }
                } else {
                    layer.msg(result.stateMsg);
                }
            }
        })
    }

    //监听区域选择
    form.on('select(areaMenu)', function (data) {
        $.removeCookie("this_motor");
        sessionStorage.removeItem("this_motor");
        $(".motorMenu").html("");
        form.render('select');
        areaId = data.value;
        getMotors(areaId);
    });

    //监听所选马达
    var motorsTitle = [];
    var motorsId = [];
    form.on('checkbox(devices)', function (data) {
        var title = $(data.elem).attr("title");
        if (data.elem.checked) {
            motorsTitle.push(title);
            motorsId.push(data.value);
        } else {
            motorsTitle = motorsTitle.filter(function (item) {
                return item != title;
            });
            motorsId = motorsId.filter(function (item) {
                return item != data.value;
            });
        }
        var title = motorsTitle.join(",");
        $(".optval").attr("value", title);
        $(".optval").attr("motorsId", motorsId);
    });

    //查询
    $(".searchBtn").click(function () {
        form.on('submit(search)', function (data) {
            searchParams = data.field;
            if (this_motor != null) {
                searchParams.exType = this_motor.exType;
                searchParams.meterID = this_motor.meterID;
            } else {
                searchParams.exType = '3';
            }
            filterObj = Object.assign({}, data.field);
            // getTableData(searchParams);
            renderTable(searchParams);
            $.removeCookie("this_motor");
            this_motor = null;
            return false;
        });
    });

    //开始时间向前推
    function getAlertTime(moId) {
        $.ajax({
            url: config.motorBaseUrl + "/mo_alert_connect/getTime/v1.0",
            type: "post",
            datatype: "json",
            async: false,
            data: {
                moId: moId
            },
            success: function (result) {
                if (result.stateCode == 0) {
                    if (result.data != null && result.data != '') {
                        $("#startDate").val(result.data);
                    }
                } else {
                    layer.msg(result.stateMsg);
                }
            }
        })
    }

    function initDate() {
        var stdate = '';
        if (this_motor != null) {
            getAlertTime(this_motor.moId);
        } else {
            stdate = new Date(new Date().toLocaleDateString());
        }
        laydate.render({
            elem: '#startDate',
            value: stdate,
            format: 'yyyy-MM-dd HH:mm:ss',
            type: 'datetime',
            max: formatDate()
        });
        laydate.render({
            elem: '#endDate',
            value: new Date(),
            format: 'yyyy-MM-dd HH:mm:ss',
            type: 'datetime',
            max: formatDate()
        });
    }

    //表格数据
    function getTableData(data) {
        $.ajax({
            url: config.motorBaseUrl + "/mo_alert_rec/select/v1.0",
            type: "post",
            datatype: "json",
            data: data,
            success: function (result) {
                if (result.stateCode == 0) {
                    renderTable(result.data);
                } else {
                    layer.msg(result.stateMsg);
                }
            }
        })
    }

    //渲染表格
    function renderTable(data) {
        tableRender = table.render({
            elem: '.reportTable'
            , id: 'exception'
            , url: config.motorBaseUrl + "/mo_alert_rec/select/v1.0"
            , method: 'post'
            , where: data
            ,request: {
                pageName: 'curr' //当前页码的参数名称，默认：page
            }
            , parseData: function (res) { //res 即为原始返回的数据
                total = res.data.total;
                return {
                    "code": res.stateCode, //解析接口状态
                    "msg": res.stateMsg, //解析提示文本
                    "count": res.data.total,
                    "data": res.data.data
                }
            }
            // , data: data
            , autoSort: false
            , cols: [[
                {field: 'areaName', title: '区域'}
                , {field: 'moName', title: '马达'}
                , {
                    field: 'strAlertTime',
                    title: '报警时间',
                    width: 170/*, templet:'<div>{{layui.util.toDateString(d.alertTime)}}</div>'*/
                }
                , {field: 'strAlertClass', title: '报警类别'}
                , {field: 'strHasDealed', title: '处理状态'}
                , {
                    field: 'strDealTime',
                    title: '处理时间',
                    width: 170/*, templet:'<div>{{ d.dealTime == null?"": layui.util.toDateString(d.dealTime)}}</div>'*/
                }
                , {field: 'dealContent', title: '处理内容'}
                , {field: 'alertMsg', title: '异常消息', width: 290}
                // , {fixed: 'right', title: '操作', width: 200, align: 'center', toolbar: '#rowOperate'}
            ]]
            , page: {
                layout: ['prev', 'page', 'next', 'count', 'skip', 'limit'] //自定义分页布局
                , groups: 1 //只显示 5 个连续页码
                , first: false
                , last: false
                , limits: [10, 20, 50, 100, 500]
            }
            , limit: limit
            , loading: true
        });
    }

    //表格操作
    table.on('tool(exceptionTable)', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;
        if (layEvent === 'deal') { //处理
            var layerIdx = layer.open({
                type: 1,
                title: "异常处理",
                closeBtn: 1,
                anim: 0,
                area: 'auto',
                content: $('#rowDeal').html(),
                success: function (layero, index) {
                    var operaCode = "";
                    var operaCodeStr = "";
                    if (data.moState == 2) {
                        operaCode = "case_open";
                        operaCodeStr = "设备维修中"
                    } else if (data.moState == 3) {
                        operaCode = "case_close";
                        operaCodeStr = "设备维修完成"
                    }
                    form.val("rowDeal", {
                        "arecId": data.arecId,
                        "operaCodeName": operaCodeStr,
                        "operaCode": operaCode
                    });
                    layero.find();
                    form.render('select');
                }
            })
            form.on('submit(rowDeal)', function (res) {
                //console.log(res.field);
                updateStatus(res.field);
                layer.close(layerIdx);
                return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
            });
            $("form button[type='cancel']").click(function () {
                layer.close(layerIdx);
                return false;
            });
        } else if (layEvent === 'goToMonitor') { //监控信息
            var goto_motor = {
                "areaId": data.areaId,
                "troughId": data.troughId,
                "moId": data.moId,
                "moName": data.moName
            };
            $.cookie("this_motor", JSON.stringify(goto_motor));
            layer.msg('即将跳转到监控信息', {
                time: 1000
            }, function () {
                var iframe = window.parent.document.getElementsByTagName('iframe')[0];
                var menulist = JSON.parse(sessionStorage.getItem("menulist"));
                if (menulist == undefined) {
                    getMenuData();
                }
                var menu = [];
                menu = menulist.filter(item => item.menuUrl === '/device/realtime')
                $(iframe).parents('div.page-content').siblings(".left-nav").find(`li#menu${menu[0].menuId}`).click();
            });
        }
    });

    function getMenuData() {
        $.ajax({
            url: config.motorBaseUrl + "/sys/getMeun/v1.0",
            type: "post",
            datatype: "json",
            data: {},
            success: function (result) {
                if (result.stateCode == 0) {
                    menulist = result.data;
                } else {
                    layer.msg(result.stateMsg);
                }

            }
        })
    }

    //修改设备状态（根据警报记录，维修中与已完成）
    function updateStatus(obj) {
        $.ajax({
            url: config.motorBaseUrl + "/mo_alert_rec/operat/v1.0",
            type: "post",
            datatype: "json",
            data: obj,
            success: function (result) {
                if (result.stateCode == 0) {
                    console.log(searchParams);
                    getTableData(searchParams);
                } else {
                    layer.alert(result.stateMsg);
                }
            }
        })
    }

    //表格重载
    function tableReload() {
        table.reload("exception", {
            url: config.motorBaseUrl + "/mo_alert_rec/select/v1.0"
            , where: searchParams
            , parseData: function (res) { //将原始数据解析成 table 组件所规定的数据
                return {
                    "code": res.stateCode, //解析接口状态
                    "msg": res.stateMsg, //解析提示文本
                    "data": res.data //解析数据列表
                };
            }
        })
    }

    //导出
    $(".exportBtn").on("click", function () {
        // excel.exportTable2Excel(tableRender, "马达异常记录");
        filterObj.curr = 1;
        filterObj.limit = total;
        var filename = '马达异常记录' + $('#startDate').val() + '-' + $('#endDate').val() + '.xlsx';
        // 重新请求，获取全部数据
        $.ajax({
            url: config.motorBaseUrl + "/mo_alert_rec/select/v1.0",
            dataType: 'json',
            type: "post",
            data: filterObj,
            beforeSend: function(){
                $(".exportBtn").addClass('layui-btn-disabled')
            },
            success: function(res) {
                var data = res.data.data;
                var exportData = []; // 需导出的数据
                var colarr = tableRender.config.cols[0]; // 页面table的表头
                var head = {}; // excel的表头
                for(var i=0;i<colarr.length;i++){
                    head[colarr[i].field] = colarr[i].title;
                }
                // 循环全部数据，按表头取出所需的字段值
                data.forEach(function(item){
                    var obj = {};
                    for(var k in head){
                        obj[k] = item[k];
                    }
                    exportData.push(obj);
                });
                exportData.unshift(head);
                excel.exportExcel({
                    sheet1: exportData
                }, filename, 'xlsx');
            },
            complete: function () {
                $(".exportBtn").removeClass('layui-btn-disabled')
            }
        });
    });

});
